<template>
  <div class="course-detail-page">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <el-button @click="goBack" link class="back-btn">
          <i class="el-icon-arrow-left"></i>
          返回
        </el-button>
        <h1 class="page-title">课程详情</h1>
      </div>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="8" animated />
    </div>

    <!-- 课程详情内容 -->
    <div v-else-if="courseDetail" class="course-detail-container">
      <!-- 课程基本信息卡片 -->
      <div class="course-info-card">
        <div class="course-header">
          <div class="course-image-container">
            <el-image
              v-if="courseDetail.courseImageUrl"
              :src="courseDetail.courseImageUrl"
              fit="cover"
              class="course-image"
              @error="handleImageError"
            />
            <div v-else class="image-placeholder">
              <i class="el-icon-picture-outline"></i>
              <span>暂无图片</span>
            </div>
          </div>
          <div class="course-info">
            <div class="category-tag">
              <i class="el-icon-folder-opened"></i>
              {{ courseDetail.lessonTypeName || "未分类" }}
            </div>
            <h2 class="course-title">{{ courseDetail.courseName }}</h2>
            <div class="course-meta">
              <span class="meta-item">
                <i class="el-icon-time"></i>
                创建时间：{{ formatDate(courseDetail.createTime) }}
              </span>
              <span class="meta-item">
                <i class="el-icon-user"></i>
                创建人：{{ courseDetail.createBy || "未知" }}
              </span>
            </div>
          </div>
        </div>
      </div>

      <!-- 课程详细信息卡片 -->
      <div class="course-details-card">
        <div class="card-header">
          <h3 class="card-title">
            <i class="el-icon-info"></i>
            课程简介
          </h3>
        </div>
        <div class="card-content">
          <div class="detail-grid">
            <p
              class="description-text"
              v-html="courseDetail.blurb || '暂无课程简介信息'"
            ></p>
          </div>
        </div>
      </div>

      <!-- 课程描述卡片 -->
      <div class="course-description-card">
        <div class="card-header">
          <h3 class="card-title">
            <i class="el-icon-document"></i>
            课程描述
          </h3>
        </div>
        <div class="card-content">
          <p class="description-text">
            {{ courseDetail.courseDescription || "暂无课程描述信息" }}
          </p>
        </div>
      </div>

      <!-- 课程视频卡片 -->
      <div
        v-if="courseDetail.video && courseDetail.video.trim()"
        class="course-video-card"
      >
        <div class="card-header">
          <h3 class="card-title">
            <i class="el-icon-video-camera"></i>
            课程视频
          </h3>
        </div>
        <div class="card-content">
          <div class="video-container">
            <video
              :src="courseDetail.video"
              controls
              class="course-video"
              preload="metadata"
              @error="handleVideoError"
              @loadstart="handleVideoLoadStart"
              @loadeddata="handleVideoLoaded"
            >
              您的浏览器不支持视频播放
            </video>
            <div v-if="videoError" class="video-error">
              <i class="el-icon-warning"></i>
              <span>视频加载失败，请检查视频链接</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 空状态 -->
    <div v-else class="empty-state">
      <el-empty description="课程信息不存在" />
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { useRouter, useRoute } from "vue-router";
import { ElMessage } from "element-plus";
import axios from "axios";

const router = useRouter();
const route = useRoute();

// 响应式数据
const loading = ref(true);
const courseDetail = ref(null);
const videoError = ref(false); // 新增：视频加载错误状态

// 获取课程详情
const getCourseDetail = async () => {
  try {
    const courseId = route.query.id;
    if (!courseId) {
      ElMessage.error("课程ID不能为空");
      return;
    }

    const response = await axios.get("/tielingpowergriduavservice/lesson/get", {
      params: { id: courseId },
    });

    if (response.data.code === 200) {
      const data = response.data.data;
      courseDetail.value = {
        id: data.id,
        courseName: data.lesson,
        blurb: data.blurb,
        video: getCourseVideoUrl(data.video),
        courseDescription: data.lessonDescription,
        lessonTypeName: data.lessonTypeName,
        courseImageUrl: getCourseImageUrl(data.lessonPhoto),
        createTime: data.createTime,
        updateTime: data.updateTime,
        createBy: data.createBy,
        updateBy: data.updateBy,
      };
      // 重置视频错误状态
      videoError.value = false;
    } else {
      ElMessage.error("获取课程详情失败：" + response.data.msg);
    }
  } catch (error) {
    ElMessage.error("请求异常：" + error.message);
  } finally {
    loading.value = false;
  }
};

function getCourseImageUrl(base64) {
  if (!base64) return "";
  try {
    if (base64.startsWith("/9j/")) {
      return "data:image/jpeg;base64," + base64;
    }
    return base64;
  } catch {
    return "";
  }
}

// 新增：处理视频URL的函数
function getCourseVideoUrl(videoData) {
  if (!videoData) return "";
  try {
    // 如果是base64编码的视频数据，需要添加正确的MIME类型前缀
    if (videoData.startsWith("AAAA") || videoData.startsWith("/9j/")) {
      // 根据数据特征判断视频格式
      let mimeType = "video/mp4"; // 默认MP4
      if (videoData.startsWith("/9j/")) {
        mimeType = "image/jpeg"; // 如果以JPEG标识开头，可能是图片
      }
      return `data:${mimeType};base64,${videoData}`;
    }

    // 如果是URL，直接返回
    if (videoData.startsWith("http://") || videoData.startsWith("https://")) {
      return videoData;
    }

    // 如果是相对路径，添加域名前缀
    if (videoData.startsWith("/")) {
      return window.location.origin + videoData;
    }

    // 如果都不是，尝试作为base64处理
    if (videoData.length > 100) {
      // 假设长字符串可能是base64
      return `data:video/mp4;base64,${videoData}`;
    }

    return videoData;
  } catch (error) {
    return "";
  }
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return "未知";
  const date = new Date(dateString);
  return date.toLocaleString("zh-CN", {
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
    hour: "2-digit",
    minute: "2-digit",
  });
};

// 图片加载错误处理
const handleImageError = () => {
  ElMessage.warning("图片加载失败");
};

// 视频加载错误处理
const handleVideoError = () => {
  videoError.value = true;
  ElMessage.error("视频加载失败，请检查视频链接");
};

// 视频加载开始
const handleVideoLoadStart = () => {
  videoError.value = false; // 重置错误状态
};

// 视频加载完成
const handleVideoLoaded = () => {
  // 视频加载成功后，如果还有错误状态，则清除
  if (videoError.value) {
    videoError.value = false;
  }
};

// 返回上一页
const goBack = () => {
  router.go(-1);
};

// 组件挂载时获取数据
onMounted(() => {
  getCourseDetail();
});
</script>

<style scoped>
.course-detail-page {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
}

.page-header {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 12px;
  padding: 20px;
  margin-bottom: 24px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
}

.header-content {
  display: flex;
  align-items: center;
  gap: 20px;
}

.back-btn {
  font-size: 16px;
  color: #409eff;
  padding: 8px 16px;
  border-radius: 8px;
  transition: all 0.3s;
}

.back-btn:hover {
  background: rgba(64, 158, 255, 0.1);
  transform: translateX(-2px);
}

.page-title {
  margin: 0;
  font-size: 28px;
  font-weight: 600;
  color: #2c3e50;
  background: linear-gradient(135deg, #667eea, #764ba2);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.loading-container {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 12px;
  padding: 40px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
}

.course-detail-container {
  max-width: 1200px;
  margin: 0 auto;
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.course-info-card {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 16px;
  padding: 32px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s ease;
}

.course-info-card:hover {
  transform: translateY(-4px);
}

.course-header {
  display: flex;
  gap: 32px;
  align-items: flex-start;
}

.course-image-container {
  flex-shrink: 0;
  width: 300px;
  height: 200px;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
}

.course-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.image-placeholder {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: #f5f7fa;
  color: #909399;
  font-size: 14px;
}

.image-placeholder i {
  font-size: 48px;
  margin-bottom: 8px;
}

.course-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.category-tag {
  display: inline-flex;
  align-items: center;
  gap: 6px;
  padding: 6px 12px;
  background: linear-gradient(135deg, #667eea, #764ba2);
  color: white;
  border-radius: 20px;
  font-size: 14px;
  font-weight: 500;
  width: fit-content;
}

.course-title {
  margin: 0;
  font-size: 32px;
  font-weight: 700;
  color: #2c3e50;
  line-height: 1.3;
}

.course-meta {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 6px;
  color: #606266;
  font-size: 14px;
}

.meta-item i {
  color: #909399;
}

.course-description-card,
.course-details-card {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 16px;
  padding: 32px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s ease;
}

.course-description-card:hover,
.course-details-card:hover {
  transform: translateY(-2px);
}

.course-video-card {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 16px;
  padding: 32px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s ease;
}

.course-video-card:hover {
  transform: translateY(-2px);
}

.card-header {
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 2px solid #f0f2f5;
}

.card-title {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
  color: #2c3e50;
  display: flex;
  align-items: center;
  gap: 8px;
}

.card-title i {
  color: #409eff;
}

.description-text {
  margin: 0;
  font-size: 16px;
  line-height: 1.8;
  color: #606266;
  text-align: justify;
}

.video-container {
  display: flex;
  justify-content: center;
  margin: 20px 0;
  position: relative; /* Added for positioning error message */
}

.course-video {
  max-width: 100%;
  max-height: 400px;
  border-radius: 12px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
  background: #000;
}

.video-error {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: rgba(255, 255, 255, 0.9);
  padding: 15px 25px;
  border-radius: 10px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2);
  display: flex;
  align-items: center;
  gap: 10px;
  color: #f56c6c;
  font-size: 14px;
  z-index: 10;
}

.video-error i {
  font-size: 20px;
}

.no-video {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 20px 0;
}

.no-video i {
  font-size: 48px;
  color: #909399;
  margin-bottom: 10px;
}

.detail-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 20px;
}

.detail-item {
  display: flex;
  align-items: center;
  padding: 12px 16px;
  background: #f8fafc;
  border-radius: 8px;
  border-left: 4px solid #409eff;
}

.detail-label {
  font-weight: 600;
  color: #2c3e50;
  margin-right: 12px;
  min-width: 80px;
}

.detail-value {
  color: #606266;
  flex: 1;
}

.action-buttons {
  display: flex;
  justify-content: center;
  gap: 16px;
  margin-top: 32px;
}

.action-buttons .el-button {
  padding: 12px 24px;
  font-size: 16px;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.action-buttons .el-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
}

.empty-state {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 16px;
  padding: 80px 40px;
  text-align: center;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .course-detail-page {
    padding: 16px;
  }

  .course-header {
    flex-direction: column;
    gap: 20px;
  }

  .course-image-container {
    width: 100%;
    height: 200px;
  }

  .course-title {
    font-size: 24px;
  }

  .course-meta {
    flex-direction: column;
    gap: 12px;
  }

  .detail-grid {
    grid-template-columns: 1fr;
  }

  .action-buttons {
    flex-direction: column;
    align-items: center;
  }
}

/* 动画效果 */
@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(30px);
  }

  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.course-info-card,
.course-description-card,
.course-details-card {
  animation: fadeInUp 0.6s ease-out;
}

.course-description-card {
  animation-delay: 0.1s;
}

.course-details-card {
  animation-delay: 0.2s;
}

.course-video-card {
  animation: fadeInUp 0.6s ease-out;
  animation-delay: 0.3s;
}
</style>
